(function() {
  var dataKey, editModel, getTrHtml, listen, saveUserData, showUserData;

  dataKey = 'qq_qqlgin';

  getTrHtml = function(qq, ps) {
    if (qq == null) {
      qq = '';
    }
    if (ps == null) {
      ps = '';
    }
    return "<tr>\n	<td>\n		<input name=\"qq[]\" type=\"text\" value=\"" + qq + "\" placeholder=\"输入QQ号\" />\n	</td>\n	<td class=\"passCol\">\n		<input name=\"password[]\" type=\"password\" value=\"" + ps + "\" placeholder=\"输入QQ密码\" />\n	</td>\n	<td>\n		<button type=\"button\" class=\"btn\">登录</button>\n	</td>\n</tr>";
  };

  editModel = function() {
    $('table').addClass('editModel');
    return $('input').removeAttr('readonly');
  };

  saveUserData = function() {
    var obj;
    obj = {};
    obj[dataKey] = $('form').serializeObject();
    return chrome.storage.local.set(obj);
  };

  showUserData = function(callback) {
    return chrome.storage.local.get(dataKey, function(item) {
      var i, obj, tbody, v, _i, _len, _ref;
      obj = {
        qq: [''],
        password: ['']
      };
      if (item && item[dataKey]) {
        obj = item[dataKey];
      }
      tbody = '';
      _ref = obj.qq;
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        v = _ref[i];
        if (tbody && !v) {
          continue;
        }
        tbody += getTrHtml(v, obj.password[i]);
      }
      $('tbody').html(tbody);
      return callback();
    });
  };

  listen = function(data) {
    var index;
    index = 0;
    return chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
      var num, password, _ref, _ref1, _results;
      if (request != null ? request.qq : void 0) {
        if (request.qq.login) {
          _results = [];
          while (true) {
            if (!$("[name='qq[]']")[index]) {
              alert('完成任务');
              break;
            }
            num = (_ref = $("[name='qq[]']")[index]) != null ? _ref.value : void 0;
            password = (_ref1 = $("[name='qq[]']")[index]) != null ? _ref1.value : void 0;
            if (num && password) {
              sendResponse({
                qq: {
                  qq: num,
                  password: password
                }
              });
              break;
            }
            _results.push(index++);
          }
          return _results;
        } else if (request.qq.next) {
          return sendResponse({
            qq: {
              next: true
            }
          });
        }
      }
    });
  };

  showUserData(function() {
    $('#save').click(saveUserData);
    $('#addLine').click(function() {
      $('tbody').append($(getTrHtml()));
      return editModel();
    });
    $('#edit').click(editModel);
    return $('form').submit(function() {
      saveUserData();
      listen();
      open('https://mail.qq.com/cgi-bin/loginpage');
      return false;
    });
  });

}).call(this);
